package com.codejoys.monitor.service.impl;

import com.codejoys.monitor.dao.UserDao;
import com.codejoys.monitor.domain.Role;
import com.codejoys.monitor.domain.User;
import com.codejoys.monitor.domain.UserRole;
import com.codejoys.monitor.dto.PageData;
import com.codejoys.monitor.dto.SysUser;
import com.codejoys.monitor.exception.SysException;
import com.codejoys.monitor.mapper.RoleMapper;
import com.codejoys.monitor.mapper.UserMapper;
import com.codejoys.monitor.mapper.UserRoleMapper;
import com.codejoys.monitor.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {
    // private static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    // private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    UserDao userDao;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Override
    public SysUser findUserByName(String name) {
        return userDao.findUserByName(name);
    }

    @Override
    public void register(User user) {
        userMapper.insertSelective(user);

        // 给用户设置一个默认的角色
        // type = 1   => role: teacher
        // type = 2   => role: student
        // user_role  =>  1,  1

        // 查询所有角色
        final List<Role> roles = roleMapper.selectByExample(null);

        Integer roleId = null;
        // 设置一个默认角色
        final Optional<Role> roleResult = roles.stream().filter(role -> {
            return "operator".equals(role.getKeyword());
        }).findFirst();

        if (roleResult.isPresent()) {
            roleId = roleResult.get().getId();
        }

        if (roleId == null) {
            throw new SysException(10000, "找不到角色id");
        }

        // 往user_role表里面插入一条记录
        UserRole userRole = new UserRole();
        userRole.setUid(user.getId());
        userRole.setRid(roleId);

        userRoleMapper.insertSelective(userRole);
    }

    @Override
    public void modifyPass(SysUser tmsUser) {


        User user = new User();
        user.setId(tmsUser.getId());
        user.setPassword(tmsUser.getPassword());
        userMapper.updateByPrimaryKeySelective(user);
    }
}
